import { watch } from 'vue'
import { useAxios } from '@http/serve'
import secret from '@/utils/secret'
import {setUserInfo, setAccount} from "@/utils/userData"
import type {UserInfoType, Result} from '@type'
interface LoginRequest {
  name: string;
  pass: string;
  code: string
}
interface LoingRes {
  in: number,
  token: string
}

export const sendLogin = (formState: LoginRequest, remember: boolean, fn: (rs:string) => void) => {
  const { data, isFinished } = useAxios('login')
  .post<LoingRes>({
    data: formState.name,
    pass: secret.SHA256(formState.pass), 
    code: formState.code
  })

  watch(isFinished,(val) => {
    // 记录登录信息
    if(remember){
      setAccount({
        UserName: formState.name,
        PassWord: formState.pass,
        isRemember: remember
      })
    }
    
    if(val){
      if(data.value?.data.in){
        console.log('第一次登录');
      }
      fn(data.value?.data.token || "")
    }
  })
}
export const sendUserInfo = <R = UserInfoType>(token: string): Promise<Result<R>> => {
  return new Promise((resolve, reject) => {
    const { data, isFinished, error } = useAxios('userInfo', {
      headers: {
        Authorization: token
      }
    }).post<UserInfoType>()
    watch([isFinished, error],([val, error]) => {
      if(val && data.value){
        setUserInfo(data.value.data,token)
        resolve(data.value)
      }
      if(error) {
        reject(error)
      }
    })
  })
}
export const sendCommonDict = <T = any>(): Promise<Result<T>> => {
  return new Promise((resolve, reject) => {
    const { data, isFinished, error } = useAxios('userInfo').post<T>()
    watch([isFinished, error],([val, error]) => {
      if(val && data.value){
        const res = data.value
        resolve(res)
      }
      if(error){
        reject(error)
      }
    })
  })
}